
<template>
    <el-tree ref="folderTreeRef" :data="folderData" node-key="catalogueId" :active="props.activeId"
        :expand-on-click-node="true" :auto-expand-parent="true"
        :default-expand-all="props.defaultExpandAll"
        :render-after-expand="false" :icon="ArrowRight" class="folder-tree" 
        :lazy="props.lazy"
        @node-click="handleNodeClick"
        :load="loadData" :indent="20" :props="defaultProps" empty-text="暂无课程目录">
        <template #default="{ data }">
            <div :class="[{'catalogue-tag': data.catalogueType === 1}, {'active': props.activeId === data.catalogueId}, fmtCatalogue(data)]">
                <span class="title">
                    <span class="title-name">
                        <ellipsis :content="data.catalogueName"/>
                    </span>
                    <!-- <span class="show-subtitle" v-if="handleSubTitle(data)">字幕</span> -->
                </span> 
                <div class="progress" v-if="isBuyPerson && data.catalogueType === 1 && !isPreview" :class="[fmtProgress(data)]">{{fmtProgressText(data)}}</div>
            </div>
        </template>
    </el-tree>
</template>

<script setup>
import { ref, computed, watch, nextTick} from 'vue';
import Ellipsis from '@/components/ellipsis.vue';
import { ArrowRight } from '@element-plus/icons-vue';
import { fmtTime } from '@/lib/biz-tools.js';
import { treeForEach } from '@/lib/tools';

const emit = defineEmits(['node-click', 'load-data']);

const props = defineProps({
    data: {
        type: Array,
        default: () => {
            return [];
        } 
    },
    lazy: {
        type: Boolean,
        default: false
    },
    defaultExpandAll: {
        type: Boolean,
        default: false  
    },
    activeId: {
        type: [String, Number],
        default: '' 
    },
    isCreater: { // 是否是创建者
        type: Boolean,
        default: false
    },
    isBuyPerson: { // 是否是购买者
        type: Boolean,
        default: false
    },
    isPreview: { // 是否是预览状态
        type: Boolean,
        default: false
    },
    courseWareStateInfoList: { // 课件对应状态列表
        type: Array,
        default: () => {
            return []
        }
    }
})

// 目录视频对应的字幕数组
const subTitleMap = ref({});

const defaultProps = {
    isLeaf: 'isLeaf',
    children: 'children',
    label: 'catalogueName',
    class: customNodeClass
}

function customNodeClass(data, node) {
    if (data.pid === '0' && data.catalogueId === props.activeId) {
        return 'catalogue-parent active'
    }
    if (data.pid === '0' && data.catalogueId !== props.activeId) {
        return 'catalogue-parent'
    }
    if (data.catalogueType === 1 && data.catalogueId === props.activeId) {
        return 'catalogue-leaf active'
    }
    if (data.catalogueType === 1 && data.catalogueId !== props.activeId) {
        return 'catalogue-leaf'
    }
    return null
}


watch(() => props.data, async (val) => {
   if(val && val.length) {
        await nextTick();
        getSubTitleList();
        props.activeId && folderTreeRef.value && folderTreeRef.value.setCurrentKey(props.activeId);  
   }
}, {immediate: true})

const folderData = computed({
    get: () => {
        return props.data
    },
    set: val => {
        return val
    }
})

// 异步加载数据
function loadData(node, callback) {
    if(props.lazy) {
        emit('load-data', node, callback);
    }
}

const folderTreeRef = ref(null);

// 点击事件
function handleNodeClick(data, node) {
    if(data.tag && !data.tag.includes('catalogue')) { // 说明是课件 非课件的tag为空或者catalogue
        folderTreeRef.value && folderTreeRef.value.setCurrentKey(data.catalogueId);
    }
    emit('node-click', data, node);
}

function fmtCatalogue(data) {
    let arr = data.tag && data.tag.split(',') || [];
    return data.catalogueType === 1 ? arr.length && arr[0] : 'catalogue';
};

// 格式化时长
function fmtDuration (data) {
    return data.courseWare?.duration ? '时长 ' + fmtTime(data.courseWare.duration) : '时长 ' + '00:00:00';
}

// 格式化进度
function fmtProgress (data) {
    let current = courseWareState(data)
    let state = current?.finishState;
    if (state == -1) {
        return 'status-not-start';
    } else if (state == 0) {
        return 'status-learing';
    } else if (state == 1) {
        return 'status-finish';
    }
}

// 格式化进度
function fmtProgressText (data) {
    let current = courseWareState(data)
    let state = current?.finishState;
    if (state == -1) {
        return '未开始';
    } else if (state == 0) {
        return `${current?.finishPercentage || 0}%`;
    } else if (state == 1) {
        return '已完成';
    }
}

function courseWareState(nodeData){
    let list = props.courseWareStateInfoList.filter(i => i.catalogueId === nodeData.catalogueId) || [];
    return list?.[0] || {};
}

// 获取字幕列表 目录有视频获取字幕
function getSubTitleList () {
    let videoIds = [];
    if (folderData.value && folderData.value.length) {
        treeForEach(folderData.value, item => {
            if (item.catalogueType === 1 && item.courseWare && item.courseWare.contentId && item.tag === 'video') {
                videoIds.push(item.courseWare.contentId);
            }
        })
    }
    if (videoIds.length > 0) {
        G_transmit('subtitleSearch', {
            data: {
                materialIds: videoIds,
                subtitleInitType: 1
            }
        }).then(async (res) => {
            subTitleMap.value = {};
            (res.data || []).forEach(item => {
                subTitleMap.value[item.materialId] = item;
            })
        }).catch((_err) => {
            console.log(_err)
        }).finally(() => {
        })
    }
}

// 控制是否显示字幕
function handleSubTitle (data) {
    if (data.catalogueType === 1 && data.tag=== 'video' && data.courseWare.contentId && subTitleMap.value[data.courseWare.contentId]) {
        return true;
    } else {
        return false
    }
}


</script>

<style lang="scss" scoped>

@mixin img-style(){
    content: '';
    width: 18px;
    height: 18px;
    display: inline-block;
    vertical-align: middle;
    margin-right: 8px;
}

.folder-tree {
    width: 100%;
    overflow: hidden;
    :deep(.catalogue-leaf) {
        .el-tree-node__expand-icon {
            display: none;
        }
    }
    :deep(.catalogue-leaf) {
        .el-tree-node__expand-icon {
            display: none;
        }
        .el-tree-node__content {
            color: var(--main-text-color);
            // border: none;
        }
    }
    :deep(.el-tree-node) {
        font-size: 14px;
        margin-bottom: 3px;
    }
    :deep(.el-tree-node__content) {
        height: 36px;
        padding-right: 25px;

        &:hover {
            background: #E7F1FF;
            border-radius: 4px;
        }
    }
    :deep(.el-tree-node__expand-icon:not(.is-leaf)) {
        color: var(--main-text-color);
    }
    :deep(.catalogue) {
        width: 100%;
        overflow: hidden;
        .title {
            width: 100%;
            color: var(--srt-main-text-color);
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
    }
    .status-not-start {
        margin-left: 11px;
        color: var(--srt-color-light-gray);
    }
    .status-learing {
        margin-left: 11px;
        color: #FF9201;
    }
    .status-finish {
        margin-left: 11px;
        color: #00B042;
    }
}

:deep(.catalogue-parent) {
    & > .el-tree-node__content {
        background: #F7F9FA;
        border-radius: 4px;
        font-size: 16px;
        font-weight: bold;
        color: var(--main-text-color);
        margin-bottom: 3px;
    }
}

:deep(.active) {
    & > .el-tree-node__content {
        background: #E7F1FF;
        .title {
            color: var(--srt-main-active-text-color);
            .duration-time {
                color: var(--srt-main-active-text-color);
            }
        }
    }
}
.catalogue-tag {
    flex: 1;
    display: flex;
    // justify-content: space-between;
    align-items: center;
    width: 100%;
    overflow: hidden;
    .title {
        color: var(--srt-main-text-color);
        display: flex;
        justify-content: flex-start;
        align-items: center;
        flex: 1;
        overflow: hidden;
        .title-name {
            display: inline-block;
            max-width: calc(100% - 200px);
            // flex: 1;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        .show-subtitle {
            color: #47698C;
            margin-left: 4px;
            padding: 0 4px;
            background: #EFF0F2;
            border-radius: 4px;
            line-height: 20px;
        }
    }
    .progress {
        font-size: 12px;
    }
    &.doc, &.docx {
        &::before {
            @include img-style();
            background: url('~@/assets/img/resource-type/doc.png') no-repeat;
            background-size: contain;
        }
    }
    &.ppt, &.pptx {
        &::before {
            @include img-style();
            background: url('~@/assets/img/resource-type/ppt.png') no-repeat;
            background-size: contain;
        }
    }
    &.xls, &.xlsx{
        &::before {
            @include img-style();
            background: url('~@/assets/img/resource-type/excel.png') no-repeat;
            background-size: contain;
        }
    }
    &.evaluate {
        &::before {
            @include img-style();
            background: url('~@/assets/img/resource-type/evaluate.png') no-repeat;
            background-size: contain;
        }
    }
    &.img {
        &::before {
            @include img-style();
            background: url('~@/assets/img/resource-type/img.png') no-repeat;
            background-size: contain;
        }
    }
    &.files {
        &::before {
            @include img-style();
            background: url('~@/assets/img/resource-type/files.png') no-repeat;
            background-size: contain;
        }
    }
    &.pdf {
        &::before {
            @include img-style();
            background: url('~@/assets/img/resource-type/pdf.png') no-repeat;
            background-size: contain;
        }
    }
    &.audio {
        &::before {
            @include img-style();
            background: url('~@/assets/img/resource-type/audio.png') no-repeat;
            background-size: contain;
        }
    }
    &.video, &.vedion {
        &::before {
            @include img-style();
            background: url('~@/assets/img/resource-type/video.png') no-repeat;
            background-size: contain;
        }
    }
    &.rest, &.unknown {
        &::before {
            @include img-style();
            background: url('~@/assets/img/resource-type/rest.png') no-repeat;
            background-size: contain;
        }
    }
    &.comment {
        &::before {
            @include img-style();
            background: url('~@/assets/img/resource-type/comment.png') no-repeat;
            background-size: contain;
        }
    }
    &.catalogue {
        &::before {
            content: '\e69c';
            font-family: 'iconfont';
            font-size: 18px;
            color: var(--main-text-color); 
            font-weight: 400;
            margin-right: 8px;
            margin-left: 2px;
        }
        padding-right: 25px;
        width: 100%;
    }
}

</style>